<?php

namespace App\Biz;



use Dcat\Admin\Traits\HasUploadedFile;
use Illuminate\Filesystem\FilesystemAdapter;

class UploadedBiz
{
    use HasUploadedFile;

    protected FilesystemAdapter $disk;

    protected VisitorReservesBiz $visitorReservesBiz;

    /**
     * @param VisitorReservesBiz $visitorReservesBiz
     */
    public function __construct(VisitorReservesBiz $visitorReservesBiz)
    {
        $this->disk  = $this->disk('admin');
        $this->visitorReservesBiz = $visitorReservesBiz;

    }

    /**
     * @return mixed
     */
    public function imageUpload(){

        // 获取上传的文件
        /**
         * @var \Symfony\Component\HttpFoundation\File\UploadedFile|void $file
         */
        $file = $this->file();

        try {

            // $fileId = 'group1/M00/22/25/EfQAeGO6S8iANXAXAAKPCZUss3E794.jpg';
            // $pathInfo = pathinfo($fileId);

            $response = $this->visitorReservesBiz->imageUpload($file);
            if (empty($response->get('fileId'))){
                throw new \Exception('获取接口fileId数据为空');
            }

            $pathInfo = pathinfo($response->get('fileId'));
            $dir = $pathInfo['dirname'];
            $newName = $pathInfo['basename'];

        } catch (\Exception $e) {

            return $this->responseErrorMessage($e->getMessage());
        }

        $result = $this->disk->putFileAs($dir, $file, $newName);

        $path = "{$dir}/$newName";

        return $result
            ? $this->responseUploaded($path, $this->disk->url($path))
            : $this->responseErrorMessage('文件上传失败');
    }

    /**
     * 图片保存
     * @param string $path
     * @param string $contents
     * @param array $options
     * @return bool|string
     */
    public function putFileAs(string $path,string $contents,array $options = []): bool|string
    {
        $result = $this->disk->put($path, $contents, $options);

        \Log::info("putFileAs result: {$result}");

        return $result;
    }
}
